//
//  HomeViewController.m
//  CYWFrame
//
//  Created by Macx on 2017/7/21.
//  Copyright © 2017年 Macx. All rights reserved.
//

#import "HomeViewController.h"


#import "SDWebImage/UIButton+WebCache.h"
#import "CCZSegementController.h"
#import <XRCarouselView.h>
#import "LCButton.h"

#import "JobViewController.h"
#import "LiveListViewController.h"
#import "JobRecommendListViewController.h"
#import "MallReccomendViewController.h"
#import "LiveContentViewController.h"
#import "HomeLiveReccomendViewController.h"
#import "JobMiddleViewController.h"

#import "JobHomeViewController.h"
#import "MallHomeViewController.h"
#import "HomeMiddleMallViewController.h"
#import "HomeMiddleLiveViewController.h"
#import "MallListViewController.h"
#import "SearchViewController.h"
#import "AllSearchViewController.h"
#import "MessageViewController.h"
#import "QAViewController.h"
#import "PostQuestionViewController.h"

#import "AdsServer.h"
#import "NotificationServer.h"

#import "AlertSignView.h"
#import "NSString+Common.h"

#import "UIButton+Badge.h"

#define STOREAPPID @"1447944401"

#define EVERYDAYSIGN @"everyDaySign"

#import "TCMsgHandler.h"
#import "privateChat.h"

#import "JPUSHService.h"
#import "ConversationListViewController.h"
#import "BaseNavViewController.h"
#import "TotalSearchViewController.h"
#import "NearbyShopViewController.h"
#import "LaunchIntroductionView.h"

@interface HomeViewController () <UIScrollViewDelegate>

@property (strong, nonatomic) NSMutableArray *btnArr;

@end

@implementation HomeViewController {
    UIButton        *_noticeBtn;
    XRCarouselView  *_carouselView;
	UIView 			*_topView;
    UIScrollView    *_scrollView;
    UIView          *_line1;
	CCZSegementController *_segementMiddle;	//新增的中间segment
	XRCarouselView          *_bannerView;	//新加的中间的Banner
    CCZSegementController *_segement;
    UIButton        *_returnBtn;
    UIView          *_lbBtnView;
    
    XRCarouselView *_carOne;
    
}

- (void)viewWillAppear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:YES animated:animated];
	
	NSInteger role = [GetUserDefaule(USERINFO)[@"role"] integerValue];
    if (role != 0) {
        [self updateNum];
    }
	if ([LZCTools thinkEnv]) {
		[self getBtnInfo];
	}
}
- (void)viewWillDisappear:(BOOL)animated {
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)updateNum {
    
    [[NetworkTool sharedTool] requestWithName:@"未读消息" URLString:APIUnreadTips parameters:nil method:@"GET" callBack:^(id responseObject) {
        
        int a = [responseObject[@"data"][@"notification"] intValue];
        int b = [responseObject[@"data"][@"message"] intValue];
        
        int count = [privateChat chatListUnReadMessageNum];
		
		_noticeBtn.shouldHideBadgeAtZero = YES;
        _noticeBtn.badgeValue = [NSString stringWithFormat:@"%d", a+b+count];
    }];
}

- (void)c2cNotification:(NSNotification *)notification {
    NSLog(@"--接收到私聊提醒通知--\n%@", notification.userInfo);
	if (![notification.userInfo isKindOfClass:[NSNull class]] && ![notification.userInfo isEqual:@"(null)"] && notification.userInfo!=nil) {
		[self updateNum];
	}
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"c2cNotification" object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"postQA" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    if (GetUserDefaule(USERINFO)) {
        //AVIMMsgHandler *msgHandler = [[AVIMMsgHandler alloc] init];
    }

    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(c2cNotification:)name:@"c2cNotification" object:nil];
	
    
    // 第一次引导图（不是第一次打开app那3张，是那三张过后的两张广告图，右上角有个x按钮的，目前貌似不用，先隐藏了）
    //[self buildGuide];
    if(![[NSUserDefaults standardUserDefaults] boolForKey:@"firstStart"]){
        [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"firstStart"];
        NSLog(@"第一次启动");
        
        //[self buildGuide];
        
    }else{
        NSLog(@"不是第一次启动");
    }
	
    [self UI1];
    [self buildUI];
    [self GETAds];
	
}

#pragma mark ==========构建UI==========
- (void)buildGuide {
	
    if (GetUserDefaule(Token) == NULL) {
        
        MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        [hud hideAnimated:YES afterDelay:1.0];
        double delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //执行事件
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            [self buildGuide];
        });
        return;
        
    }
	
    NSMutableArray *imgArr = [[NSMutableArray alloc] init];
    [[NetworkTool sharedTool] requestWithName:@"获取引导图" URLString:APIAds parameters:@{@"board":@"app_guide"} method:@"GET" callBack:^(id responseObject) {
        for (NSDictionary *dic in responseObject[@"data"]) {
            [imgArr addObject:dic[@"photo"]];
        }
        
        self.navigationController.tabBarController.tabBar.hidden = YES;
        
        _carOne = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
        _carOne.imageArray = imgArr;
        _carOne.contentMode = UIViewContentModeScaleAspectFit;
        _carOne.backgroundColor = kBlackColor;

        UIButton *releaseBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        releaseBtn.frame = CGRectMake(SCREEN_WIDTH-SCREEN_WIDTH/5, SCREEN_HEIGHT-SCREEN_WIDTH/5,SCREEN_WIDTH/6, SCREEN_WIDTH/6);
        [self.view addSubview:releaseBtn];
        [releaseBtn setImage:[UIImage imageNamed:@"icon_close_w"] forState:UIControlStateNormal];
        [releaseBtn addTarget:self action:@selector(postClick:) forControlEvents:UIControlEventTouchUpInside];
    }];
}

- (void)postClick:(UIButton *)sender {
    
    [sender removeFromSuperview];
    [_carOne removeFromSuperview];
    
    self.navigationController.tabBarController.tabBar.hidden = NO;
    
}
- (void)UI1 {
    // 不知道为什么tabbar默认第一个不高亮，只能选择默认第二个，然后在跳回第一个
    self.tabBarController.selectedIndex = 1;
    self.tabBarController.selectedIndex = 0;
    
    self.view.backgroundColor = kWhiteColor;
	
    UIView *fakeStatusBar = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, Height_StatusBar)];
	fakeStatusBar.backgroundColor = UIMainColorRGB;
	//[self.view addSubview:fakeStatusBar];
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, -Height_StatusBar, SCREEN_WIDTH, SCREEN_HEIGHT)];
    [self.view addSubview:_scrollView];
    _scrollView.delegate = self;
	
	//topView
	_topView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SW(5)*2.5)];
	//UIImageView *topImageView = [UIImageView imageViewWithImage:IMAGE(@"zhaopin")];
	//topImageView.size = _topView.size;
	
	//轮播图
	_carouselView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, _topView.height)];
	//[_scrollView addSubview:_carouselView];
	_carouselView.contentMode = UIViewContentModeScaleAspectFill;
	_carouselView.imageArray = @[IMAGE(@"img.jpg")];
	_carouselView.time = 2;
	[_topView addSubview:_carouselView];
	[_scrollView addSubview:_topView];
	
	//搜索栏
    UISearchBar *searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, SCREEN_WIDTH-50, 30)];
	if(IS_IPHONE_X || IS_IPHONE_Xr) {
		searchBar.frame = CGRectMake(0, 40, SCREEN_WIDTH-50, 30);
	}
    searchBar.placeholder = @"请输入搜索内容…";
    searchBar.backgroundImage = IMAGE(@"clearImage");
    searchBar.layer.cornerRadius = searchBar.height/2;
    searchBar.layer.masksToBounds = YES;
    UIView *searchTextField = searchTextField = [searchBar valueForKey:@"_searchField"];
    searchTextField.backgroundColor = [UIColor colorWithRed:234/255.0 green:235/255.0 blue:237/255.0 alpha:1];
    [_scrollView addSubview:searchBar];
    
    UIView *searView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, searchBar.width, searchBar.height)];
    [searchBar addSubview:searView];
    [searView addTarget:self action:@selector(searchClicK:)];
	
	
    _noticeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_scrollView addSubview:_noticeBtn];
    [_noticeBtn setImage:IMAGE(@"index_notice") forState:UIControlStateNormal];
    _noticeBtn.frame = CGRectMake(searView.x+searView.width, searchBar.y, SCREEN_WIDTH-(searView.x+searView.width), 30);
    [_noticeBtn addTarget:self action:@selector(noticeClick:)];
//    _noticeBtn.badgeValue = @"1";
    _noticeBtn.badgeBGColor = kRedColor;
	
}

- (void)buildUI {
	if (GetUserDefaule(Token) == NULL) {
		
		MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
		[hud hideAnimated:YES afterDelay:1.0];
		double delayInSeconds = 1.0;
		dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
		dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
			//执行事件
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[self buildUI];
		});
		return;
	}
	
    NSDictionary *userInfo = GetUserDefaule(USERINFO);
    NSLog(@"主页注册极光 user_id %@", userInfo);
    
    if (userInfo != NULL) {
        [JPUSHService setAlias:userInfo[@"user_id"] completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
            NSLog(@"别名 aliad %ld %@ %ld", iResCode, iAlias, seq);
        } seq:999];
    }
    [self createUINormal];
}

- (void)createUINormal {
	_line1 = [[UIView alloc] initWithFrame:CGRectMake(0, _topView.y+_topView.height, SCREEN_WIDTH, 1)];
	[_scrollView addSubview:_line1];
	_line1.backgroundColor = UISeparatedColorRGB;
	if ([LZCTools thinkEnv]) {
		_lbBtnView = [[UIView alloc] initWithFrame:CGRectMake(0, _topView.height+_topView.y, SCREEN_WIDTH, SW(6)*2+SW(15))];
		[_scrollView addSubview:_lbBtnView];
		
		for (int i = 0; i < 12; i++) {
			
			CGFloat btnX = 0.0f;
			CGFloat btnY = 0.0f;
			LCButton *indexBtn;
			
			if (i < 5) {
				btnX = SW(36)+SW(4.8)*i;
				btnY = SW(27);
			}
			else{
				btnX = SW(36)+SW(4.8)*(i-5);
				btnY = SW(27)+SW(5.5);
			}
			
			indexBtn = [[LCButton alloc] initWithFrame:CGRectMake(btnX, btnY, SW(9), SW(9))];
			indexBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
			[indexBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
			[_lbBtnView addSubview:indexBtn];
			indexBtn.tag = 21+i;
			[indexBtn addTarget:self action:@selector(lbBtnClick:) forControlEvents:UIControlEventTouchUpInside];
			[self.btnArr addObject:indexBtn];
		}
		_line1.frame = CGRectMake(0, _lbBtnView.y+_lbBtnView.height, SCREEN_WIDTH, 1);
	}
    
    //NSArray *type = @[@"shop", @"broadcast", @"job"];
	NSArray *type = @[@"shop", @"job"];
    NSMutableArray *vcArr = [[NSMutableArray alloc] init];
    NSMutableArray *segmentBtnImg = [[NSMutableArray alloc] init];
    NSMutableArray *segmentBtnImgSelected = [[NSMutableArray alloc] init];
    HomeMiddleMallViewController *MiddleMallVC = [[HomeMiddleMallViewController alloc] init];
    JobMiddleViewController *MiddlejobListVC = [[JobMiddleViewController alloc] init];
    //HomeMiddleLiveViewController *MiddleLiveListVC = [[HomeMiddleLiveViewController alloc] init];
    for (int i = 0; i < type.count; i++) {
        switch (i) {
            case 0:
                [vcArr addObject:MiddleMallVC];
				[segmentBtnImg addObject:IMAGE(@"home_tablist_0")];
				[segmentBtnImgSelected addObject:IMAGE(@"home_tablist_0_curr")];
                break;
            case 1:
                [vcArr addObject:MiddlejobListVC];
				[segmentBtnImg addObject:IMAGE(@"home_tablist_2")];
				[segmentBtnImgSelected addObject:IMAGE(@"home_tablist_2_curr")];
                break;
            default:
                break;
        }
		/*
        [segmentBtnImg addObject:[UIImage imageNamed:[NSString stringWithFormat:@"home_tablist_%d",i]]];
        [segmentBtnImgSelected addObject:[UIImage imageNamed:[NSString stringWithFormat:@"home_tablist_%d_curr",i]]];
		 */
    }
    
    //中间的segment
    NSInteger roleInt = [GetUserDefaule(USERINFO)[@"role"] integerValue];
    if (roleInt == 5 || roleInt == 6) {
        _segementMiddle = [CCZSegementController segementControllerWithFrame:CGRectMake(0, _line1.y+_line1.height, SCREEN_WIDTH, 185) titles:@[@"商城",@"人才"]];
    }
    else {
        _segementMiddle = [CCZSegementController segementControllerWithFrame:CGRectMake(0, _line1.y+_line1.height, SCREEN_WIDTH, 185) titles:@[@"商城",@"岗位"]];
    }
    [_segementMiddle setSegementViewControllers:vcArr];
    _segementMiddle.style = CCZSegementStyleDefault;
    [_segementMiddle setSegementTintColor:UIMainColorRGB];
    [_segementMiddle setButtonImages:segmentBtnImg];
    [_segementMiddle setButtonImagesSelected:segmentBtnImgSelected];
    [_scrollView addSubview:_segementMiddle.view];
    [self addChildViewController:_segementMiddle];
    [_segementMiddle selectedNavAtIndex:^(NSInteger index) {
        NSLog(@"middle index %ld",index);
    }];
    
    //放Banner的View
    _bannerView = [[XRCarouselView alloc] initWithFrame:CGRectMake(0, _segementMiddle.view.frame.origin.y+_segementMiddle.view.height+10, SCREEN_WIDTH, SW(6.5)*2)];
    _bannerView.contentMode = UIViewContentModeScaleAspectFill;
    _bannerView.imageArray = @[IMAGE(@"enter_map")];
    _bannerView.time = 2;
	_bannerView.tag = 1010;
    __weak __typeof(self) weakSelf = self;
    _bannerView.imageClickBlock = ^(NSInteger index) {
        NSLog(@"banner was clicked");
        NearbyShopViewController *nearByVC = [[NearbyShopViewController alloc] init];
        [weakSelf.navigationController pushViewController:nearByVC animated:YES];
    };
    [_scrollView addSubview:_bannerView];
    
    NSMutableArray *vcArr2 = [[NSMutableArray alloc] init];
	NSMutableArray *segmentBtnImg2 = [[NSMutableArray alloc] init];
	NSMutableArray *segmentBtnImgSelected2 = [[NSMutableArray alloc] init];
    MallReccomendViewController *shopVC = [[MallReccomendViewController alloc] init];
    JobRecommendListViewController *jobListVC = [[JobRecommendListViewController alloc] init];
	HomeLiveReccomendViewController *liveListVC = [[HomeLiveReccomendViewController alloc] init];
	liveListVC.tagId = @"";
	for (int i = 0; i < 3; i++) {
		switch (i) {
			case 0:
				[vcArr2 addObject:shopVC];
				[segmentBtnImg2 addObject:IMAGE(@"home_tablist_0")];
				[segmentBtnImgSelected2 addObject:IMAGE(@"home_tablist_0_curr")];
				break;
			case 1:
				[vcArr2 addObject:jobListVC];
				[segmentBtnImg2 addObject:IMAGE(@"home_tablist_2")];
				[segmentBtnImgSelected2 addObject:IMAGE(@"home_tablist_2_curr")];
				break;
			default:
				break;
		}
	}
	//下方Segment
	if (roleInt == 5 || roleInt == 6) {
		_segement = [CCZSegementController segementControllerWithFrame:CGRectMake(0, _bannerView.y+_bannerView.height+15, SCREEN_WIDTH, SCREEN_HEIGHT-Height_NavBar-5) titles:@[@"推荐商城",@"推荐人才"]];
	}
	else {
		_segement = [CCZSegementController segementControllerWithFrame:CGRectMake(0, _bannerView.y+_bannerView.height+15, SCREEN_WIDTH, SCREEN_HEIGHT-Height_NavBar-5) titles:@[@"推荐商城",@"推荐岗位"]];
	}
	[_segement setSegementViewControllers:vcArr2];
	_segement.style = CCZSegementStyleDefault;
	[_segement setSegementTintColor:UIMainColorRGB];
	[_segement setButtonImages:segmentBtnImg2];
	[_segement setButtonImagesSelected:segmentBtnImgSelected2];
	[_scrollView addSubview:_segement.view];
	
	//为了迁就招聘首页，默认是不能滑动的，此处开放
	jobListVC.jobListTableView.scrollEnabled = YES;
	[self addChildViewController:_segement];
	[_segement selectedNavAtIndex:^(NSInteger index) {
		NSLog(@"index %ld",index);
	}];
	
	// 返回btn
	_returnBtn = [UIButton buttonWithType:UIButtonTypeCustom];
	[self.view addSubview:_returnBtn];
	[_returnBtn setBackgroundImage:IMAGE(@"btn_return_top") forState:UIControlStateNormal];
	[_returnBtn addTarget:self action:@selector(segReturnClick:) forControlEvents:UIControlEventTouchUpInside];
	_returnBtn.frame = CGRectMake(SCREEN_WIDTH-70, SCREEN_HEIGHT*1.2, 50, 50);
	_returnBtn.alpha = 0.9;
	
	_scrollView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT+_bannerView.y+_bannerView.height);
	[self checkTime];
}


#pragma mark ===========响应方法==========

- (void)lbBtnClick:(LCButton *)sender {
    
    if (sender.tag == 10) {
        [self.navigationController pushViewController:[[QAViewController alloc] init] animated:YES];
    }
    else if (sender.tag == 11) {
		
    }
    else if (sender.tag == 12) {
        [self.navigationController pushViewController:[[MallHomeViewController alloc] init] animated:YES];
    }
    else if (sender.tag == 13) {
        LiveListViewController *liveVC = [[LiveListViewController alloc] init];
        [self.navigationController pushViewController:liveVC animated:YES];
    }
    else {
		
		LiveListViewController *livelistVC = [[LiveListViewController alloc] init];
        livelistVC.defaultIndex = sender.tag-21;
		[self.navigationController pushViewController:livelistVC animated:YES];
    }
}

// 获取广告
- (void)GETAds {
    [AdsServer GETAds:@{@"board":@"app_index"} xrView:_carouselView];
	//[AdsServer GETAds:@{@"board":@"app_index_middle"} xrView:_bannerView];
}

- (void)segReturnClick:(UIButton *)sender {
	[UIView animateWithDuration:0.5 animations:^{
		_returnBtn.frame = CGRectMake(SCREEN_WIDTH-70, SCREEN_HEIGHT*1.2, 50, 50);
	}];
    _line1.hidden = NO;
    _lbBtnView.hidden = NO;
    _scrollView.delegate = nil;
    _scrollView.scrollEnabled = YES;
    CGPoint offect = _scrollView.contentOffset;
    offect.y = - _scrollView.contentInset.top-Height_StatusBar;
    [_scrollView setContentOffset:offect animated:NO];
    _scrollView.delegate = self;
    [NotificationServer homeSendNotificaiontName:@"homeRoll" param:@{@"isRoll":@"0"}];
}

#pragma mark ===========代理方法==========
// 用户开始拖拽时调用
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    NSLog(@"begin = %f", scrollView.contentOffset.y);
}
// 滚动到某个位置时调用
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if (scrollView.contentOffset.y > _bannerView.y+_bannerView.height+15-(Height_StatusBar+15)) {
        scrollView.scrollEnabled = NO;
        scrollView.delegate = nil;
        [scrollView setContentOffset:CGPointMake(0, _bannerView.y+_bannerView.height+15-(Height_StatusBar+15)) animated:NO];
        _returnBtn.hidden = NO;
		[UIView animateWithDuration:0.5 animations:^{
			_returnBtn.frame = CGRectMake(SCREEN_WIDTH-70, SCREEN_HEIGHT*0.75, 50, 50);
		}];
        _line1.hidden = YES;
        _lbBtnView.hidden = YES;
//        _line1.y=_scrollView.contentSize.height;
        
        [NotificationServer homeSendNotificaiontName:@"homeRoll" param:@{@"isRoll":@"1"}];
    }
}
// 用户结束拖拽时调用
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate {
    NSLog(@"end = %f", scrollView.contentOffset.y);
}

// 站内信点击
- (void)noticeClick:(UIButton *)sender {
    NSLog(@"点击站内信");
    if (GetUserDefaule(USERINFO) == NULL) {
        [self presentViewController:[LZCTools alertMessage:@"请先登录"]animated:YES completion:nil];
    }
    else {
//        [self.navigationController pushViewController:[[MessageViewController alloc] init] animated:YES];
        [self.navigationController pushViewController:[[ConversationListViewController alloc] init] animated:YES];
    }
}

- (void)searchClicK:(id)sender {
	TotalSearchViewController *vc = [[TotalSearchViewController alloc] init];
	[self.navigationController pushViewController:vc animated:YES];
}

- (void)getBtnInfo {
	if (GetUserDefaule(Token) == NULL) {
		
		MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
		[hud hideAnimated:YES afterDelay:1.0];
		double delayInSeconds = 1.0;
		dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
		dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
			//执行事件
			[MBProgressHUD hideHUDForView:self.view animated:YES];
			[self getBtnInfo];
		});
		return;
	}
	
	NSMutableArray *imgArr = [[NSMutableArray alloc] init];
	NSMutableArray *textArr = [[NSMutableArray alloc] init];
	[[NetworkTool sharedTool] requestWithName:@"获取首页按钮图片&标题" URLString:APIIndexTagList parameters:nil method:@"POST" callBack:^(id responseObject) {
		for (NSDictionary *dict in responseObject[@"data"])
		{
			[imgArr addObject:[dict valueForKey:@"icon"]];
			[textArr addObject:[dict valueForKey:@"name"]];
		}
		for (int i = 0; i < imgArr.count; i++) {
			
			CGFloat btnX = 0.0f;
			CGFloat btnY = 0.0f;
			LCButton *indexBtn;
			
			if (i < 5) {
				btnX = SW(36)+SW(4.8)*i;
				btnY = SW(27);
			}
			else{
				btnX = SW(36)+SW(4.8)*(i-5);
				btnY = SW(27)+SW(5.5);
			}
			
			indexBtn = self.btnArr[i];
			[indexBtn setTitle:textArr[i] forState:UIControlStateNormal];
			indexBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
			[indexBtn setTitleColor:kGrayColor forState:UIControlStateNormal];
			
			[indexBtn sd_setImageWithURL:[NSURL URLWithString:imgArr[i]] forState:UIControlStateNormal];
			
			NSLog(@"the image name is %@", imgArr[i]);
			[_lbBtnView addSubview:indexBtn];
			indexBtn.tag = 21+i;
			[indexBtn addTarget:self action:@selector(lbBtnClick:) forControlEvents:UIControlEventTouchUpInside];
		}
	}];
}

- (void)checkTime {
	// 先获取当前工程项目版本号
	NSDictionary *infoDic=[[NSBundle mainBundle] infoDictionary];
	NSLog(@"%@",infoDic);
	NSString *currentVersion = infoDic[@"CFBundleShortVersionString"];
	//NSLog(@"当前版本：%@",currentVersion);
	
	
	// 从网络获取AppStore版本号
	__block NSError *jsonError;
	// STOREAPPID是你在AppStore对应自己App的ID 可在AppStore上找到 也可在iTunesConnect上找到
	NSURLSession *session = [NSURLSession sharedSession];
	NSURLSessionDataTask *task = [session dataTaskWithRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"https://itunes.apple.com/cn/lookup?id=%@",@"1447944401"]]] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
		
		NSDictionary *appInfoDic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:&jsonError];
		if (jsonError) {
			NSLog(@"UpdateAppError:%@",jsonError);
			return;
		}
		
		NSArray *array = appInfoDic[@"results"];
		if (array.count < 1) {
			NSLog(@"此APPID为未上架的APP或者查询不到");
			return;
		}
		
		NSDictionary *dic = array[0];
		NSLog(@"返回的dic是%@",dic);
		NSString *appStoreVersion = dic[@"version"];
		//打印版本号
		NSLog(@"当前版本号:%@\n商店版本号:%@",currentVersion,appStoreVersion);
		
		
		// 当前版本号小于商店版本号,就更新
		if([currentVersion compare:appStoreVersion] == NSOrderedAscending) {
			UIAlertController *alercConteoller = [UIAlertController alertControllerWithTitle:@"版本有更新" message:[NSString stringWithFormat:@"检测到新版本(%@),是否更新?",dic[@"version"]] preferredStyle:UIAlertControllerStyleAlert];
			UIAlertAction *actionYes = [UIAlertAction actionWithTitle:@"更新" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
				//此处加入自己应用在AppStore的地址，方便用户去更新，一种实现方式如下
				NSURL *url = [NSURL URLWithString:@"itms-apps://itunes.apple.com/cn/app/id1447944401?mt=8"];
				/*
				 AXWebViewController *vc = [[AXWebViewController alloc] initWithURL:url];
				 [self.navigationController pushViewController:vc animated:YES];
				 */
				[[UIApplication sharedApplication] openURL:url options:@{} completionHandler:nil];
			}];
			UIAlertAction *actionNo = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
				
			}];
			[alercConteoller addAction:actionYes];
			[alercConteoller addAction:actionNo];
			[self presentViewController:alercConteoller animated:YES completion:nil];
		}else{
			NSLog(@"版本号比商店大 检测到不需要更新");
		}
		
	}];
	[task resume];
	
	
}

- (NSMutableArray *)btnArr
{
	if (!_btnArr) {
		_btnArr = [[NSMutableArray alloc] init];
	}
	return _btnArr;
}

-(BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
